#include "hardware_flash.h"

int Hardware_Flash_Erase(void){
	unsigned int i = 0 ,j = 0;
	FLASH_Unlock(FLASH_MEMTYPE_PROG);
	/* Wait until Flash Program area unlocked flag is set*/
	while (FLASH_GetFlagStatus(FLASH_FLAG_PUL) == RESET){
		if(i ++ >1000){
			goto exit;
		}
	}
	for(i = HARDWARE_FLASH_START_ADD;i <= HARDWARE_FLASH_END_ADD;i += 4){
		FLASH_ProgramWord(i, (uint32_t)0);		
	}
	FLASH_Lock(FLASH_MEMTYPE_PROG);
	return 0;
	exit:
		FLASH_Lock(FLASH_MEMTYPE_PROG);
		return -1;
}

/*
	num : (1-8)
*/
int Hardware_Flash_Write(int num,unsigned char *buf,unsigned int length)
{ 
	unsigned int i = 0 ,j = 0 ,start_addr = 0;
	start_addr = HARDWARE_FLASH_START_ADD + PER_PICTURE_LENGTH *(num-1);
	FLASH_Unlock(FLASH_MEMTYPE_PROG);
	/* Wait until Flash Program area unlocked flag is set*/
	while (FLASH_GetFlagStatus(FLASH_FLAG_PUL) == RESET){
		if(i ++ >1000){
			goto exit;
		}
	}
	for(i = start_addr,j = 0;i < start_addr + PER_PICTURE_LENGTH;i +=4,j += 4) {
		FLASH_ProgramWord(i, ((uint32_t)buf[j])<<24 | ((uint32_t)buf[j+1])<<16 | ((uint32_t)buf[j+2])<<8  | (uint32_t)buf[j+3]);
	}
	FLASH_Lock(FLASH_MEMTYPE_PROG);
	return 0;
	exit:
		FLASH_Lock(FLASH_MEMTYPE_PROG);
		return -1;
}

int Hardware_Flash_Read(int num,unsigned char *buf,unsigned int length)
{ 
	unsigned int i = 0 ,j = 0 ,start_addr = 0;
	start_addr = HARDWARE_FLASH_START_ADD + PER_PICTURE_LENGTH *(num-1);
	FLASH_Unlock(FLASH_MEMTYPE_PROG);
	/* Wait until Flash Program area unlocked flag is set*/
	while (FLASH_GetFlagStatus(FLASH_FLAG_PUL) == RESET){
		if(i ++ >1000){
			goto exit;
		}
	}
	for(i = start_addr,j = 0;i < start_addr + PER_PICTURE_LENGTH;i++,j++){
		buf[j] = FLASH_ReadByte(i);
	}
	FLASH_Lock(FLASH_MEMTYPE_PROG);
	return 0;
	exit:
		FLASH_Lock(FLASH_MEMTYPE_PROG);
		return -1;
}



